#!/usr/bin/python
# -*- coding: UTF-8 -*-


import re

import xlrd

import creat_excel_android

# 生成新的语言包路径
new_strings_path = '../strings_new.xml'


def read_excel():
    wb = xlrd.open_workbook(creat_excel_android.save_excel_path)
    sheet = wb.sheet_by_index(0)
    dict = {}
    for index in range(0, sheet.nrows):
        # print sheet.cell(index, 0).value
        # print sheet.cell(index, 1).value
        dict[sheet.cell(index, 0).value] = sheet.cell(index, 2).value
    if len(dict) <= 0:
        raise NameError('请检查表格是否为空，或者不为空的表格在第一个位置')

    return dict


def read_res():
    dict = read_excel()
    if len(dict) <= 0:
        return
    arry = []

    f = open(creat_excel_android.string_file, encoding='utf-8')
    line = f.readline()
    while line:
        if line is not None and len(line) > 1:
            nameSearch = re.search(creat_excel_android.pattern, line, 0)

            if nameSearch is None:
                # print(nameSearch)
                arry.append(line)
                line = f.readline()
                continue
            # print nameSearch
            key = nameSearch.group('key')
            if key in dict:
                value = dict.get(key)
                group = nameSearch.group('value')
                # print(group,value)
                newline = line.replace(group, value, 1)
                # print(newline)
                arry.append(newline)

        line = f.readline()
    f.close()
    return arry


def write_file(name='new_strings.xml'):
    array = read_res()
    with open(name, 'w', encoding='utf-8') as f:
        in_array = (line for line in array)
        f.writelines(in_array)
    print('执行成功,文件生成路径：', f.name)
    f.close()


def main():
    # read_excel()
    write_file(new_strings_path)


if __name__ == "__main__":
    main()
